package cn.orange.ch08_backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * LC77.组合
 */
public class LC77 {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> trace = new LinkedList<>();
        backtracking(1, n, k, trace, result);
        return result;
    }

    private void backtracking(int start, int n, int k, LinkedList<Integer> trace, List<List<Integer>> result) {
        if (k == 0) {
            result.add(new ArrayList<>(trace));
            return;
        }
        for (int i = start; i <= n; i++) {
            if (n - i + 1 < k) continue; //剩余长度不足时直接剪枝
            trace.add(i);
            backtracking(i + 1, n, k - 1, trace, result);
            trace.removeLast();
        }
    }

    public static void main(String[] args) {
        LC77 alg = new LC77();
        System.out.println(alg.combine(4, 2));
    }
}
